package cn.edu.sdjzu.xg23.kcsj01_backend.controller;

import cn.edu.sdjzu.xg23.kcsj01_backend.service.FileService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("files") MultipartFile[] files) {
        System.out.println("开始文件上传");
        try {
            Map<String, Object> uploadResult = fileService.uploadFiles(files);
            return Result.success(uploadResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "文件上传失败：" + e.getMessage());
        }
    }




    @GetMapping("/download")
    public void downloadFile(@RequestParam("filePath") String filePath,
                             HttpServletResponse response) throws IOException {
        // 直接调用服务层下载方法，不返回Result对象
        boolean success = fileService.downloadFile(filePath, response);
        if (success){
            System.out.println("文件下载成功");
        }
        // 如果下载失败，设置错误状态码
        if (!success) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}
